package com.jp.knowledge.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.IntegralActivity;
import com.jp.knowledge.my.activity.IntegralBuyActivity;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.PayIntegralSelectView;
import com.jp.knowledge.view.PaySelectView;

import org.xutils.view.annotation.ViewInject;

/**
 * Created by 528787067@qq.com on 2017/6/14.
 */

public class PayIntegralActivity extends SlidingActivity implements View.OnClickListener {

    @ViewInject(R.id.pay_integral_head_icon)
    private ImageView toHeadIcon;
    @ViewInject(R.id.pay_integral_user_name)
    private TextView toUserName;
    @ViewInject(R.id.pay_integral_select)
    private PayIntegralSelectView integralSelectView;
    @ViewInject(R.id.pay_integral_my_head)
    private ImageView myHeadIcon;
    @ViewInject(R.id.pay_my_integral)
    private TextView myIntegral;
    @ViewInject(R.id.pay_remain_integral)
    private TextView remainIntegral;
    @ViewInject(R.id.pay_integral_commit)
    private TextView payCommit;

    private String scoopId;
    private String userId;
    private String userName;
    private String userIcon;
    private UserData userData;
    private int userIntegral;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;
    private Dialog integralInsufficientDialog;

    @Override
    protected int getResourceId() {
        return R.layout.activity_pay_integral;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        scoopId = intent.getStringExtra("scoopId");
        userId = intent.getStringExtra("userId");
        userName = intent.getStringExtra("userName");
        userIcon = intent.getStringExtra("userIcon");

        try {
            userData = application.getUserData();
        } catch (Exception e){
            userData = null;
        }
        if(userData != null){
            userIntegral = userData.getIntegralNum();
            ImageLoadUtil.loadCircle(mContext, userData.getPortrait(), myHeadIcon);
        }
        ImageLoadUtil.loadCircle(mContext, userIcon, toHeadIcon);
        if(userName != null)
            toUserName.setText(userName);

        initTitle();
        initBroadcase();
        initIntegralDialog();
        myIntegral.setText(userIntegral + "币");
        if(integralSelectView.getSelectIntegral() < 0)
            remainIntegral.setText(myIntegral.getText());
        else
            remainIntegral.setText((userIntegral-integralSelectView.getSelectIntegral()) + "币");
        payCommit.setOnClickListener(this);
        integralSelectView.setOnSelectedNumChangedListener(new PaySelectView.OnSelectedNumChangedListener() {
            @Override
            public void onSelectedNumChanged(int num) {
                if(num < 0)
                    remainIntegral.setText(myIntegral.getText());
                else
                    remainIntegral.setText((userIntegral-num) + "币");
            }
        });
    }

    private void initTitle(){
        rightBtn.setText("历史");
        topName.setText("打赏");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setVisibility(View.VISIBLE);
        rightBtn.setVisibility(View.VISIBLE);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
        leftIcon.setOnClickListener(this);
        rightBtn.setOnClickListener(this);
    }

    private void initBroadcase(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                if(LocalBroadCast.GET_LOGIN_INFO.equals(intent.getAction())){
                    try {
                        userData = application.getUserData();
                    } catch (Exception e){
                        userData = null;
                    } finally {
                        if(userData != null)
                            userIntegral = userData.getIntegralNum();
                        myIntegral.setText(userIntegral + "币");
                        if(integralSelectView.getSelectIntegral() < 0)
                            remainIntegral.setText(myIntegral.getText());
                        else
                            remainIntegral.setText((userIntegral-integralSelectView.getSelectIntegral()) + "币");
                    }
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    private void initIntegralDialog(){
        integralInsufficientDialog = new Dialog(mContext, R.style.custom_idalgo);
        View dialogContentView = View.inflate(mContext, R.layout.dialog_integral_insufficient, null);
        dialogContentView.findViewById(R.id.integral_buy).setOnClickListener(this);
        integralInsufficientDialog.setContentView(dialogContentView);
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.right_bn:
                startActivity(new Intent(mContext, IntegralActivity.class));
                break;
            case R.id.pay_integral_commit:
                final int selectedIntegral = integralSelectView.getSelectIntegral();
                if(selectedIntegral < 0){
                    ToasUtil.toast(mContext, "请选择有效的打赏知识币");
                } else if(userIntegral < selectedIntegral){
                    integralInsufficientDialog.show();
                } else if(selectedIntegral < 10){
                    ToasUtil.toast(mContext, "打赏不能低于10知识币");
                } else{
                    JsonObject param = new JsonObject();
                    param.addProperty("userId", userId);
                    param.addProperty("scoopId", scoopId);
                    param.addProperty("integral", selectedIntegral);
                    HttpHelper.getInstance(mContext).rewardIntegral(param, 0x01, new ResultSubscriber.OnResultListener() {
                        @Override
                        public void onStart(int requestType) {
                            loading.show();
                        }
                        @Override
                        public void onCompleted(int requestType) {
                            loading.cancel();
                        }
                        @Override
                        public void onError(int requestType) {
                            onCompleted(requestType);
                        }
                        @Override
                        public void onNext(IModel data, int requestType) {
                            if(data.getErrcode() != 0){
                                ToasUtil.toast(mContext, data.getMessage());
                            } else{
                                ToasUtil.toast(mContext, "打赏成功");
                                userData.setIntegralNum(userIntegral - selectedIntegral);
                                localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.GET_LOGIN_INFO));
                                setResult(RESULT_OK, getIntent());
                                finish();
                            }
                        }
                    });
                }
                break;
            case R.id.integral_buy:
                mContext.startActivity(new Intent(mContext, IntegralBuyActivity.class));
                integralInsufficientDialog.cancel();
                break;
        }
    }
}
